//
//  BaseModel.m
//  Maylida
//
//  Created by Laojingxing on 2018/4/13.
//  Copyright © 2018年 laojingxing. All rights reserved.
//

#import "BaseModel.h"
#import "NSDictionary+Utils.h"

@implementation BaseModel

+ (id)instanceWithDict:(NSDictionary *)dict
{
    return [dict isKindOfClass:[NSDictionary class]] ? [[self alloc] initWithDictionary:dict] : nil;
}

- (instancetype)initWithDictionary:(NSDictionary *)dic
{
    self = [super init];
    if (self) {
        static NSString *setMethodString = @"set%@:";
        static SEL selector = NULL;
        NSEnumerator *enumerator = [dic keyEnumerator];
        id key;
        
        while ((key = [enumerator nextObject]))
        {
            // 如果键不是string类型，那就不做处理
            if (![key isKindOfClass:[NSString class]]) continue;
            
            // 获取当前model 的类名
            NSString *classNameString = [NSString stringWithUTF8String:object_getClassName(self)];
            // 把类名转成类
            id class = NSClassFromString(classNameString);
            
            // 属性名
            NSString *curMappingKey = key;
            // 判断某些key是否需要重新映射 比如字典里的key 有关键字 id这些东西。
            if ([[class mappingKey] isForKeyExists:key]) {
                
                curMappingKey = [class mappingKey][key];
            }
            
            id obj = [dic safeObjectForKey:key];
            
            if ([[NSNull null] isEqual:obj]) continue;
            // 拼接set方法
            selector = NSSelectorFromString([NSString stringWithFormat:setMethodString, [self keyProcess:curMappingKey]]);
            if (selector != NULL && [self respondsToSelector:selector])
                [self setValue:obj forKey:curMappingKey];
        }
        selector = NULL;
    }
    return self;
}

+ (NSDictionary*)mappingKey{
    
    return nil;
}

- (NSString *)keyProcess:(NSString *)key
{
    if ([key length] == 0 || islower([key characterAtIndex:0]) == 0) return key;
    return [[key substringToIndex:1].uppercaseString stringByAppendingString:[key substringFromIndex:1]];
}
@end
